import request from '../request/request.js'

let global = {
	appId: 'wx25a46180d285a05a',
	appSecret: '',
	userInfo: {
		openid: null,//通过appId发送请求获取appSecret，再通过appSecret发送请求获取openid
		session_key: null,
	},
	// 请求函数
	getAppSercret: function() {
		request({
			url: '/api/Sys_WeChat/GetAppSercret',
			method: 'GET',
			data:{
				appId: global.appId,
			},
			success:function(scs) {
				global.appSecret=scs.data.data.appSercret;
			},
			fail:function(fl) {
			}
		})
	},
	// 获取openid和session_key
	getOpenId: function(getform = "js") {
		global.getAppSercret();
       try{
		   var that = this
		   wx.login({
		   	// provider: 'weixin',
		   	success: function(res) {
		   		let code = res.code;
		   		let callback = function(data) {
		   			that.userInfo.openid = data.openid;
		   			that.userInfo.session_key = data.session_key;
		   		}
		   		switch (getform) {
		   			case 'js':
		   				that.getOpenIdByJs(code, callback);
		   				break;
		   			default:
		   				that.getOpenIdByPHP(code, callback);
		   				break;
		   		}
		   
		   	}
		   })
	   }catch(fl) {
		   console.log('报错:', fl);
	   }
	},
	// 通过code获取openid和session_key
	getOpenIdByJs: function(code, callback) {
		try {
			if(global.appSecret=='') {
				console.log('appSct为空');
			}
			console.log("appSecret为",global.appSecret);
			wx.request({
				url: 'https://api.weixin.qq.com/sns/jscode2session',
				data: {
					appid: global.appId,
					secret: global.appSecret, //通过应用密匙获取openid和session_key
					js_code: code,
					grant_type: 'authorization_code',
				},
				success: (res) => {
					console.log('openid为',res.data.openid);
					uni.setStorage({
						key: 'openid',
						data: res.data.openid,
					});
					callback(res.data);
				},
				fail: (res) => {
					uni.showError(res.data);
				},
			});
		} catch (getO) {
			console.log('报错:', getO);
		}

	},
	//获取用户的手机号
	getMobile(encryptedData, iv) {
		
		try {
			let data = this.decodeWxData(encryptedData, iv);
			uni.setStorage({
				key: 'shoujihao',
				data: data.phoneNumber,
			});
			uni.setStorage({
				key: 'appid',
				data: data.watermark.appid,
			});
			return data.phoneNumber;
		} catch (getM) {
			console.log('报错:', getM)
		}

	},
	// 微信公用的解密算法
	decodeWxData: function(encryptedData, iv) {
		try {
			var WXBizDataCrypt = require('@/common/WXBizDataCrypt.js');
			var pc = new WXBizDataCrypt(this.appId, this.userInfo.session_key);//不发送请求，openid和session_key未定义，所以手机号未定义
			var data = pc.decryptData(encryptedData, iv); //{键值对}/////////-------------------报错位置-----
			return data;
		} catch (dec) {
			//TODO handle the exception
			console.log('报错:',dec);
		}
	},

};

module.exports = global;
